//
//  HMStatusesViewModel.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/17.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//  单元格cell的视图模型,用来处理cell显示的数据

import UIKit

class HMStatusesViewModel: NSObject {

    var iconURl: URL?
    
    var verifitedImage: UIImage?
    
    var mbRankImage: UIImage?
    
    // 微博来源
    var sourceText: String?
    
    var rowHeight: CGFloat = 300
    
    // 原创微博的属性字符串
    var originAttributedString: NSMutableAttributedString?
    
    // 转发微博的属性字符串
    var retweetedAttributedString: NSMutableAttributedString?
    
    
    // 用get是因为这样才能保证在不刷新微博的时候也能刷新时间(单元格cell重用的时候刷新)
    var timeText: String? {
        //1.实例化日期格式化对象
        let dateFormater = DateFormatter()
        //2.指定格式化符
        dateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //在真机上必须设置本地化信息否则转换失败
        dateFormater.locale = Locale(identifier: "en")
        //3.将字符串转换日期对象
        guard let sinaDate = dateFormater.date(from: statues?.created_at ?? "") else {
            return "来自火星"
        }

        //4.处理日期
        //4.1 判断是否是今年 Calendar 提供非常丰富的日期处理函数
        let calender = Calendar.current
        let currentDate = Date()
        let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        if result.year == 0 {
            //今年
            if calender.isDateInToday(sinaDate) {
                //今天
                //获取当前时间和sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinaDate)
                if delta < 60 {
                    //刚刚
                    return "刚刚"
                } else if delta < 3600 {
                    return "\(Int(delta / 60))分钟前"
                } else {
                    return "\(Int(delta / 3600))小时前"
                }
            } else if calender.isDateInYesterday(sinaDate) {
                //昨天 昨天 HH:mm
                dateFormater.dateFormat = "昨天 HH:mm"
                return dateFormater.string(from: sinaDate)
            } else {
                //其他 MM-dd HH:mm
                dateFormater.dateFormat = "MM-dd HH:mm"
                return dateFormater.string(from: sinaDate)
            }
        } else {
            //非当年
            dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormater.string(from: sinaDate)
        }
    }

    
    //计算型的属性,判断应该返回什么类型微博的pic_urls
    var imageURLs: [HMPictureInfo]? {
        if statues?.retweeted_status == nil {
            //原创微博
            return statues?.pic_urls
        }
        //转发微博
        return statues?.retweeted_status?.pic_urls
        
        

    }
    
    
    var statues: HMStatuses? {
        didSet {
            iconURl = URL(string: statues?.user?.avatar_large ?? "")
            
            self.dealWeiboVerifitrdImage()
            
            self.dealWeiboVerifitrdImage()
            
            self.sourceText = dealWeiboSource(source: statues?.source ?? "")
            
            self.originAttributedString = dealWeivoText(str: statues?.text ?? "")
            self.retweetedAttributedString = dealWeivoText(str: statues?.retweeted_status?.text ?? "")
        }
    }
    
    private func dealWeivoText(str: String) -> NSMutableAttributedString {
        
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        // 查找
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        let strM = NSMutableAttributedString(string: str)
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight

        
        // 遍历
        for result in results.reversed() {
            
            
            let range = result.rangeAt(0)
            let sub = (str as NSString).substring(with: range)
            // 根据表情字符串在表情数组中查找对应的表情模型(图片路径)
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs: sub) {
                
                let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
                let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignTo:font , alignment: .center)
                strM.replaceCharacters(in: range, with: imageText)
            }
            
        }
        strM.addAttributes([NSFontAttributeName : font], range: NSRange(location: 0, length: strM.length))
       
        
        addHighlighted(pattern: "@\\w+", strM: strM)
        addHighlighted(pattern: "#.*?#", strM: strM)
        addHighlighted(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strM)

        return strM
    }
    
    //给特殊文本添加高亮
    private func addHighlighted(pattern: String,strM: NSMutableAttributedString) {
        //先给@某人
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let str = strM.string
        //2. 通过规则在字符串中查找目标字符串 --> [NSTextCheckResult]
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        for result in results {
            let range = result.rangeAt(0)
            //let sub = (str as NSString).substring(with: range)
            //给目标字符串添加颜色
            strM.addAttributes([NSForegroundColorAttributeName : UIColor.orange], range: range)
      
            
            let border = YYTextBorder(fill: UIColor.red, cornerRadius: 4)
            let heighLight = YYTextHighlight()
            
            heighLight.setColor(UIColor.orange)
            heighLight.setBackgroundBorder(border)
            strM.yy_setTextHighlight(heighLight, range: range)
        }
        
    }

    
    private func dealWeiboSource(source: String) -> String {
        //<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">iPhone 6s 土豪金</a>
        let startFlag = "\">"
        let endFlag = "</a>"
        guard let startRange = source.range(of: startFlag),
            let endRange = source.range(of: endFlag) else {
                return "来自火星"
        }
        
        //upperBound 最大边界 lowerBound: 最小边界
        let range = startRange.upperBound..<endRange.lowerBound
        let subStr = source.substring(with: range)
        return subStr
    }

    
    // 处理用户等级图片
    private func dealMbrankImage() {
        let mbrabk = statues?.user?.mbrank ?? 0
        
        if mbrabk > 0 && mbrabk < 7 {
            mbRankImage = UIImage(named: "common_icon_membership_level\(mbrabk)")
        }
    }

    // 处理认证
    private func dealWeiboVerifitrdImage() {
        
        let type = statues?.user?.verified_type ?? -1
        
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            verifitedImage = nil
        }
    }
    
    //处理数据相关的业务逻辑 处理微博日期,微博来源
    
}
